package com.kantboot.system.user.dao.repository.vo;

import com.kantboot.system.user.domain.dto.SysUserOfAdminSearchDTO;
import com.kantboot.system.user.domain.vo.SysUserOfAdminVO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface SysUserOfAdminVORepository extends JpaRepository<SysUserOfAdminVO, Long> {

    /**
     * 获取用户列表
     * 查询是否在线时，要有以下标准：
     *  1、u.userOnline不为null
     *  2、最后一次心跳时间不为null
     *  3、u.userOnline.isOnline为true
     *  4、最后一次心跳时间小于 当前时间减3分钟
     * @param param 查询参数
     * @return 用户列表
     */
    @Query("""
    FROM SysUserOfAdminVO AS u
    LEFT JOIN SysUserRole AS ur ON u.id = ur.userId
    WHERE
    (:#{#param.id} IS NULL OR u.id = :#{#param.id})
    AND (:#{#param.username} IS NULL OR :#{#param.username} = '' OR u.username LIKE CONCAT('%',:#{#param.username},'%'))
    AND (:#{#param.nickname} IS NULL OR :#{#param.nickname} = '' OR u.nickname LIKE CONCAT('%',:#{#param.nickname},'%'))
    AND (:#{#param.directCode} IS NULL OR :#{#param.directCode} = '' OR u.directCode LIKE CONCAT('%',:#{#param.directCode},'%')) 
    AND (:#{#param.inviteCode} IS NULL OR :#{#param.inviteCode} = '' OR u.inviteCode LIKE CONCAT('%',:#{#param.inviteCode},'%'))
    AND (:#{#param.inviteUserId} IS NULL OR u.inviteUserId = :#{#param.inviteUserId})
    AND (:#{#param.phone} IS NULL OR :#{#param.phone} = '' OR u.phone LIKE CONCAT('%',:#{#param.phone},'%'))
    AND (:#{#param.email} IS NULL OR :#{#param.email} = '' OR u.email LIKE CONCAT('%',:#{#param.email},'%'))
    AND (:#{#param.genderCode} IS NULL OR :#{#param.genderCode} = '' OR u.genderCode = :#{#param.genderCode} )
    AND (:#{#param.introduction} IS NULL OR :#{#param.introduction} = '' OR u.introduction LIKE CONCAT('%',:#{#param.introduction},'%'))
    AND (:#{#param.isTemporary} IS NULL OR u.isTemporary = :#{#param.isTemporary})
    AND (:#{#param.roleCodes} IS NULL OR ur.roleCode IN (:#{#param.roleCodes}))
    ORDER BY u.id DESC
    """)
    Page<SysUserOfAdminVO> getBodyData(@Param("param") SysUserOfAdminSearchDTO param,
                                              Pageable pageable);

}
